/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.pro.service;

import com.thinkgem.jeesite.common.mapper.JsonMapper;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.common.utils.CacheUtils;
import com.thinkgem.jeesite.common.utils.MailUtil;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.pro.dao.ProjectDao;
import com.thinkgem.jeesite.modules.pro.dao.ProjectUserDao;
import com.thinkgem.jeesite.modules.pro.dao.TaskGroupDao;
import com.thinkgem.jeesite.modules.pro.entity.ProLog;
import com.thinkgem.jeesite.modules.pro.entity.Project;
import com.thinkgem.jeesite.modules.pro.entity.ProjectUser;
import com.thinkgem.jeesite.modules.pro.entity.TaskGroup;
import com.thinkgem.jeesite.modules.sys.entity.Role;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 项目管理功能Service
 * @author fanqinglong
 * @version 2017-04-13
 */
@Service
public class ProjectService extends CrudService<ProjectDao, Project> {
	@Autowired
	private TaskGroupDao taskGroupDao;
	@Autowired
	private ProjectUserDao projectUserDao;
	@Autowired
	private ProLogService proLogService;
	@Autowired
	private SystemService systemService;

	public Project get(String id) {
		return super.get(id);
	}
	
	public List<Project> findList(Project project) {
		List<Role> roleList = UserUtils.getUser().getRoleList();
		boolean flag = true;
		for (Role role : roleList) {
			//项目管理员身份
			if ("project_manager".equals(role.getEnname())) {
				flag = false;
				break;
			}
		}
		if (flag) {
			project.getSqlMap().put("dsf", "and a.id in ( SELECT ppu.project_id FROM pro_project_user ppu WHERE ppu.user_id = " + UserUtils.getUser().getId() + ")");
		}
		return super.findList(project);
	}
	
	public Page<Project> findPage(Page<Project> page, Project project) {
		//dataScopeFilter(project, "dsf", null, "");
		List<Role> roleList = UserUtils.getUser().getRoleList();
		boolean flag = true;
		for (Role role : roleList) {
			//项目管理员身份
			if ("project_manager".equals(role.getEnname())) {
				flag = false;
				break;
			}
		}
		if (flag) {
			project.getSqlMap().put("dsf", "and a.id in ( SELECT ppu.project_id FROM pro_project_user ppu WHERE ppu.user_id = '" + UserUtils.getUser().getId() + "')");
		}
		return super.findPage(page, project);
	}
	
	@Transactional(isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRED,readOnly = false, rollbackFor = Exception.class)
	public void save(Project project) {
		boolean flag = StringUtils.isEmpty(project.getId());
		User manager = systemService.getUser(project.getManager().getId());
		//如果是新增了一个项目，要新增一个默认任务分组
		if (StringUtils.isEmpty(project.getId())) {
			project.preInsert();
			TaskGroup taskGroup = new TaskGroup();
			taskGroup.setName("默认分组");
			taskGroup.setProject(project);
			taskGroup.preInsert();
			taskGroupDao.insert(taskGroup);
			//新增项目的时候，默认添加一个项目成员为负责人本身
			ProjectUser projectUser = new ProjectUser();
			projectUser.preInsert();
			projectUser.setUser(project.getManager());
			projectUser.setProjectId(project.getId());
			//项目负责人拥有该项目所有权限
			projectUser.setCode(31);
			//发送邮件
			if (!StringUtils.isEmpty(manager.getEmail())) {
				StringBuffer sb = new StringBuffer();
				sb.append(manager.getName());
				sb.append(",你已成为[");
				sb.append(project.getName());
				sb.append("]项目的负责人");
				MailUtil.SendMail(manager.getEmail(), "项目增加通知", sb.toString());
			}
			projectUserDao.insert(projectUser);
			dao.insert(project);
		}else {
			// 修改负责人的时候，默认添加这个人到项目并且授予所有权限
			ProjectUser projectUser = new ProjectUser();
			projectUser.setUser(project.getManager());
			projectUser.setProjectId(project.getId());
			ProjectUser result = projectUserDao.getByParam(projectUser);
			if (null == result) {
				result = projectUser;
				result.preInsert();
				result.setCode(31);
				projectUserDao.insert(result);
			}else {
				result.setCode(31);
				result.preUpdate();
				projectUserDao.update(result);
			}
			super.save(project);
		}
		//项目日志
		ProLog proLog = new ProLog();
		proLog.setModule(ProLog.PROJECT);
		proLog.setModuleid(project.getId());
		proLog.setData(JsonMapper.toJsonString(project));
		proLog.setType(flag?ProLog.CREATE:ProLog.UPDATE);
		proLog.setProject(project);
		proLogService.save(proLog);

	}
	
	@Transactional(isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRED,readOnly = false, rollbackFor = Exception.class)
	public User assignUserToProject(Project project,User user){
		if (user == null){
			return null;
		}
		List<String> projectIdList = user.getProjectIdList();
		if (projectIdList.contains(project.getId())) {
			return null;
		}
		//添加中间表信息
		ProjectUser projectUser = new ProjectUser();
		projectUser.preInsert();
		projectUser.setUser(user);
		projectUser.setProjectId(project.getId());
		projectUserDao.insert(projectUser);
		//清除缓存
		CacheUtils.remove(UserUtils.USER_CACHE, UserUtils.USER_CACHE_ID_ + user.getId());
		CacheUtils.remove(UserUtils.USER_CACHE, UserUtils.USER_CACHE_LOGIN_NAME_ + user.getLoginName());
		//发送邮件
		if (!StringUtils.isEmpty(user.getEmail())) {
			StringBuffer sb = new StringBuffer();
			sb.append(user.getName());
			sb.append(",你已成为[");
			sb.append(project.getName());
			sb.append("]项目的成员");
			MailUtil.SendMail(user.getEmail(), "人员分配通知", sb.toString());
		}
		return user;
	}
	
	@Transactional(isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRED,readOnly = false, rollbackFor = Exception.class)
	public void delete(Project project) {
		super.delete(project);
		//项目日志
		ProLog proLog = new ProLog();
		proLog.setModule("项目");
		proLog.setModuleid(project.getId());
		proLog.setData(JsonMapper.toJsonString(project));
		proLog.setType(ProLog.DELETE);
		proLog.setProject(project);
		proLogService.save(proLog);
	}
	
	public Project getByName(Project project) {
		return dao.getByName(project);
	}
	
	public List<Project> getJsonForTree(Project project) {
		return dao.getJsonForTree(project);
	}
	
	/**
	 * 移除人员
	 * @param project
	 * @param user
	 * @return
	 */
	@Transactional(isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRED,readOnly = false, rollbackFor = Exception.class)
	public Boolean outProject(Project project , User user){
		try {
			ProjectUser projectUser = new ProjectUser();
			projectUser.setProjectId(project.getId());
			projectUser.setUser(user);
			projectUserDao.delete(projectUser);
			//清除缓存
			CacheUtils.remove(UserUtils.USER_CACHE, UserUtils.USER_CACHE_ID_ + user.getId());
			CacheUtils.remove(UserUtils.USER_CACHE, UserUtils.USER_CACHE_LOGIN_NAME_ + user.getLoginName());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		return true;
	}
}